import Router from '@koa/router'

// import api from '../api.js'
import { glob } from 'glob'
import config, { saveConfig } from '../config/index.js'
import path from 'path'
import fsPromises from 'fs/promises'
import { sleep } from '../util.js'

import parserApi from '../api/parser.js'
import pdfApi from '../api/pdf.js'
import gptPdfApi from '../api/gpt-pdf.js'
import grokApi from '../api/grok.js'
import deepseekApi from '../api/deepseek.js'

import dbWeb from '../lib/doubao/doubao-web.js'
import { pdfToReportPrompt } from '../lib/llm/prompt.js'
import gpt from '../lib/gpt/gpt.js'
import grok from '../lib/grok/grok.js'

export default app => {
  const router = new Router()

  router.get('/db/go', async ctx => {
    await dbWeb.go()

    ctx.body = {
      code: 0,
    }
  })

  router.get('/db/upload', async ctx => {
    pdfApi.uplpad()

    ctx.body = {
      code: 0,
    }
  })

  router.get('/gpt/go', async ctx => {
    await gpt.go()

    ctx.body = {
      code: 0,
    }
  })

  router.get('/gpt/upload', async ctx => {
    gptPdfApi.uplpad()

    ctx.body = {
      code: 0,
    }
  })

  router.get('/grok/upload', async ctx => {
    grokApi.uplpad()

    ctx.body = {
      code: 0,
    }
  })

  router.get('/lhbd/fix', async ctx => {
    ctx.body = {
      code: 0,
    }

    setTimeout(async () => {
      let files = await glob('D:/研判知识库压缩包/酒仙桥六号部队 - 未采集成功/*.txt')

      if (config.lhbdFixIndex == undefined) config.lhbdFixIndex = 0

      for (let i = config.lhbdFixIndex; i < files.length; i++) {
        // 进度
        console.log(`${i}/${files.length}`, ((i / files.length) * 100).toFixed(2))

        config.lhbdFixIndex = i
        const file = files[i]
        const pdfPath = path.join('D:/研判知识库压缩包/酒仙桥六号部队 - pdf', path.parse(file).name + '.pdf')

        const result = await dbWeb.upload(pdfPath, pdfToReportPrompt)

        fsPromises.writeFile(
          path.join('D:/研判知识库压缩包/酒仙桥六号部队 - 手动修复', path.parse(file).name + '.txt'),
          result
        )

        saveConfig()

        await sleep(45 * 1000)
      }
    }, 1000)
  })

  router.get('/lhbd/fix', async ctx => {})

  router.get('/chat', parserApi.extractDetectionAndMitigation)

  router.get('/ds/go', deepseekApi.go)
  router.get('/ds/chat', deepseekApi.chat)
  router.get('/ds/conversation', deepseekApi.conversation)

  app.use(router.routes()).use(router.allowedMethods())
}
